import $ from 'jquery'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {
	Session
} from '@/utils/storage';

export default {
	ajax(options, showLoading = true) {
		let that = this
		let loading
		if (showLoading) NProgress.start()
		let appPath = this.baseURL


		//let appPath = "https://www.weifeibangbang.com/"
		//let appPath = "http://localhost:8081/"

		//console.log(typeof options['data'])
		if (typeof options['data'] != 'string' && options['url'].indexOf('/userLogin/login') == -1) {
			if (options['data']) {
				if (!options['data']['ticketId']) options['data']['ticketId'] = Session.get('token')
				options['data']['source'] = "app"
			} else {
				options['data'] = {};
				options['data']['ticketId'] = Session.get('token')
				options['data']['source'] = "app"
			}
		}
		let ajaxData = {};

		ajaxData['type'] = options['type'] || 'post';
		ajaxData['url'] = appPath + options['url'];

		if (ajaxData['url'].indexOf("ticketId") == -1 && Session.get('token')) {
			ajaxData['url'] = ajaxData['url'] + "?ticketId=" + Session.get('token')
		}
		if (options['data']) {
			if (typeof options['data'] == 'string') {
				let thisData = JSON.parse(options['data']);
				thisData.ticketId = Session.get('token')
				options['data'] = JSON.stringify(thisData)
			}
			ajaxData['data'] = options['data'];
		}

		ajaxData['dataType'] = 'json';
		if (options['contentType'] == 'application/json') {
			ajaxData['Content-Type'] = options['contentType'];
			ajaxData['contentType'] = options['contentType']
		}
		ajaxData['async'] = options['async'] == false ? false : true;

		if (localStorage.getItem("user")) {
			let user = JSON.parse(localStorage.getItem("user"))
			if (user.entType == "DIS_FACILITATOR") {
				if (localStorage.getItem("custom")) {
					let custom = JSON.parse(localStorage.getItem("custom"))
					//console.log("sssss",custom.entId)
					ajaxData['headers'] = {
						"entId": custom.entId
					}
				} else {
					//if(this.$route.path != "/customs" && !this.$route.path.includes("/waterManage")) return that.$router.push("/customs")
				}
			}
		}
		if (localStorage.getItem("entId")) {
			ajaxData['headers'] = {
				"entId": localStorage.getItem("entId")
			}
		}

		ajaxData['success'] = function(data) {
			//console.log(data)
			if (showLoading) NProgress.done();
			if (!data.success) data.msg && console.error(data.msg);
			if (data.status == -1) {
				Session.clear();
				// 使用 reload 时，不需要调用 resetRoute() 重置路由
				return that.$router.push("/login");
			}
			if (data.status == -4) {
				if (localStorage.getItem("isNoRight")) {
					setTimeout(function() {
						localStorage.removeItem("isNoRight")
					}, 2000)
				} else {
					localStorage.setItem("isNoRight", true)
					return that.$confirm(data.infoList[0], '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						localStorage.removeItem("isNoRight")
					}).catch(() => {
						localStorage.removeItem("isNoRight")
					});
				}
			}

			//console.log(options['success'](data),options['success'])
			if (data.status == -5) return that.$router.push("/activated?ticketId=" + Session.get('token'));
			options['success'] && options['success'](data);
		}

		ajaxData['error'] = function(error) {
			if (showLoading) NProgress.done();
			if (options['error']) {
				options['error'](error);
			} else {
				console.error(error.status, error.responseText);
			}
		}
		$.ajax(ajaxData);
	},

	getQueryString(name) {
		const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
		let thisTextHash = decodeURIComponent(window.location.hash)
		if (reg && thisTextHash && thisTextHash.split("?") && thisTextHash.split("?")[1]) {
			const r = thisTextHash.split("?")[1].match(reg)
			if (r) return unescape(r[2])
		}
		return null
	},
}